/**
 * title: Form and Table data binding
 * desc: useAntdTable returns a search object after receiving a form instance.
 *
 * title.zh-CN: Form 与 Table 联动
 * desc.zh-CN: useAntdTable 接收 form 实例后，会返回 search 对象。
 */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable no-unused-vars */
import React, { useState, useEffect } from 'react';
import { Form, Input, Table, Select, Button, Space, Modal, Spin, message } from 'antd';

import { useBoolean } from 'ahooks';
import { If } from 'babel-plugin-jsx-control-statements';

import RequestApi from '../../../utils/request';
import css from './index.scss';

/**
 * 停车单位管理
 */
export default () => {
	const [form] = Form.useForm();
	const [addForm] = Form.useForm();
	const [isModalVisible, setIsModalVisible] = useState(false);
	const [loading] = useBoolean(false);
	const [data, setData] = useState(); // 存放表格数据
	// 查询按钮
	// 通过区域名字提取到districtId
	const [districtListState, setDistrictListState] = useState();
	useEffect(() => {
		RequestApi.connection('get', `district/getList`).then((res) => {
			setDistrictListState(res.data);
		});
	}, []);
	const districtList = [];
	if (districtListState !== undefined && districtListState !== null) {
		districtListState.map((item) => {
			const district = {};
			district.id = item.id;
			district.districtName = item.name;
			districtList.push(district);
			if (item.sonArea !== null) {
				item.sonArea.map((sonAreaItem) => {
					const newDistrict = {};
					newDistrict.id = sonAreaItem.id;
					newDistrict.districtName = sonAreaItem.name;
					districtList.push(newDistrict);
					return null;
				});
			}
			return null;
		});
		const cqDistric = {};
		cqDistric.id = 1;
		cqDistric.districtName = '重庆市';
		districtList.push(cqDistric);
	}
	const onFinish = (values) => {
		if (values.districtId === undefined) {
			values.districtId = null;
		}
		if (values.name === undefined) {
			values.name = null;
		}
		if (values.status === undefined) {
			values.status = null;
		}
		RequestApi.connection('post', `orgnization/getOrgList`, values).then((res) => {
			setData(res.data);
		});
	};

	const onFinishFailed = (errorInfo) => {
		console.log('Failed:', errorInfo);
	};
	// 重置按钮
	const reset = () => {
		RequestApi.connection('post', `orgnization/getOrgList`).then((res) => {
			setData(res.data);
		});
		form.setFieldsValue({
			districtId: null,
			name: null,
			status: null,
		});
	};

	// 获取上级单位信息
	const orgData = [];
	if (data !== null && data !== undefined) {
		data.map((item) => {
			const orgMsg = {};
			orgMsg.parentOrgId = item.id;
			orgMsg.parentOrgName = item.parentOrgName;
			orgData.push(orgMsg);
			return null;
		});
	}

	// 新增单位
	const add = () => {
		setIsModalVisible(true);
	};
	// const [addFormvalues, setAddFormvalues] = useState();
	const onFinishAddForm = (values) => {
		if (districtList !== null && districtList !== undefined) {
			districtList.map((item) => {
				if (item.districtName === values.districtName) {
					values.districtId = item.id;
				}
				return null;
			});
		}
		if (orgData !== null && orgData !== undefined) {
			orgData.map((item) => {
				if (item.parentOrgName === values.parentOrgName) {
					values.parentOrgId = item.parentOrgId;
				}
				return null;
			});
		}
		RequestApi.connection('post', `orgnization/add`, values)
			.then(() => {
				message.success('保存成功');
			})
			.catch(() => {
				message.error('保存失败！！');
			});
		addForm.setFieldsValue({
			districtId: null,
			name: null,
			districtName: null,
			contact: null,
			tel: null,
			address: null,
			remark: null,
			orgName: null,
		});
	};

	const handleCancel = () => {
		setIsModalVisible(false);
		addForm.setFieldsValue({
			districtId: null,
			name: null,
			districtName: null,
			contact: null,
			tel: null,
			address: null,
			remark: null,
			orgName: null,
		});
	};

	// 获取表格信息
	const distinctNameList = []; // 用于存放区域列表
	useEffect(() => {
		RequestApi.connection('post', `orgnization/getOrgList`).then((res) => {
			setData(res.data);
		});
	}, []);

	if (data !== undefined && data !== null) {
		data.map((item) => {
			if (!distinctNameList.includes(item.districtName)) {
				distinctNameList.push(item.districtName);
			}
			return null;
		});
	}
	// console.log('data:', data);
	// 用于获取单位名字和单位Id
	const orgIdAndName = [];
	if (data !== null && data !== undefined) {
		data.map((item) => {
			const orgMsg = {};
			orgMsg.id = item.id;
			orgMsg.orgName = item.name;
			orgIdAndName.push(orgMsg);
			return null;
		});
	}
	// console.log('orgIdAndName:', orgIdAndName);
	// 改变禁用启用状态
	const statusChange = (status, orgName) => {
		// 从 orgName获取到districtId
		if (data !== undefined && data !== null) {
			let id = 1;
			orgIdAndName.map((item) => {
				if (orgName === item.orgName) {
					id = item.id;
				}
				return null;
			});
			if (status === 1) {
				status = 0;
			} else {
				status = 1;
			}
			// 获取单位id和状态
			RequestApi.connection('get', `/orgnization/updateOrgStatus/${status}/${id}`)
				.then(() => {
					RequestApi.connection('post', `orgnization/getOrgList`).then((res) => {
						setData(res.data);
					});
					// console.log('newdata:', data);
					message.success('修改状态成功');
				})
				.catch(() => {
					message.error('修改状态失败！！');
				});
		}
	};

	const columns = [
		{
			title: '功能列',
			dataIndex: '',
			render: (text, record) => {
				return (
					<Space>
						<Button type="link">编辑</Button>
						<If condition={record.status === 1}>
							<Button type="link" onClick={() => statusChange(record.status, record.name)} style={{ color: 'red' }}>
								禁用
							</Button>
						</If>
						<If condition={record.status === 0}>
							<Button type="link" onClick={() => statusChange(record.status, record.name)}>
								启用
							</Button>
						</If>
					</Space>
				);
			},
		},
		{
			title: '行政区域',
			dataIndex: 'districtName',
		},
		{
			title: '单位名称',
			dataIndex: 'name',
		},
		{
			title: '上级单位名称',
			dataIndex: 'parentOrgName',
		},
		{
			title: '状态',
			dataIndex: 'status',
			render: (text, record) => {
				return (
					<Space>
						<If condition={text === 0}>
							<p>禁用</p>
						</If>
						<If condition={text === 1}>
							<p>启用</p>
						</If>
					</Space>
				);
			},
		},
		{
			title: '联系人',
			dataIndex: 'contact',
		},
		{
			title: '联系电话',
			dataIndex: 'tel',
		},
		{
			title: '地址',
			dataIndex: 'address',
		},
		{
			title: '备注',
			dataIndex: 'remark',
		},
	];

	return (
		<>
			<Form form={form} className={css.table_list_form} onFinish={onFinish} onFinishFailed={onFinishFailed}>
				<Space>
					<Form.Item name="districtId" label="区域 ">
						<Select style={{ width: 150 }} placeholder="请选择区域" allowClear>
							<If condition={districtList !== null && districtList !== undefined}>
								{districtList.map((item, index) => (
									<Select.Option value={item.id} key={item.id}>
										{item.districtName}
									</Select.Option>
								))}
							</If>
						</Select>
					</Form.Item>
					<Form.Item name="name" label="单位名称： ">
						<Input placeholder="请输入关键字" style={{ width: 200 }} allowClear />
					</Form.Item>
					<Form.Item name="status" label="状态: ">
						<Select style={{ width: 150 }} placeholder="请选择状态" allowClear>
							<Select.Option value="1">启用</Select.Option>
							<Select.Option value="0">禁用</Select.Option>
						</Select>
					</Form.Item>
					<div className={css.button}>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button onClick={reset}>重置</Button>
						<Button type="primary" style={{ marginLeft: 560 }} onClick={add}>
							新增单位
						</Button>
						<Modal visible={isModalVisible} onCancel={handleCancel} width={700} footer={[]}>
							<Form
								name="addCompany"
								form={addForm}
								onFinish={onFinishAddForm}
								labelCol={{ span: 3 }}
								style={{ marginTop: 20 }}
							>
								<Form.Item label="区域:" name="districtName" rules={[{ required: true, message: '区域不能为空' }]}>
									<Select placeholder="请选择区域" filterOption={false} showSearch>
										<If condition={districtList !== null && districtList !== undefined}>
											{districtList.map((item, index) => (
												<Select.Option value={item.districtName} key={item.id}>
													{item.districtName}
												</Select.Option>
											))}
										</If>
									</Select>
								</Form.Item>
								<Form.Item label="单位名称:" name="name" rules={[{ required: true, message: '单位名称不能为空' }]}>
									<Input type="text" placeholder="请填写单位名称" />
								</Form.Item>
								<Form.Item
									label="所属单位:"
									name="parentOrgName"
									rules={[{ required: true, message: '所属单位不能为空' }]}
									style={{ marginTop: 5 }}
								>
									<Select placeholder="请选择上级管理单位:" filterOption={false} showSearch>
										<If condition={orgData !== null && orgData !== undefined}>
											{orgIdAndName.map((item, index) => (
												<Select.Option value={item.orgName} key={item.id}>
													{item.orgName}
												</Select.Option>
											))}
										</If>
									</Select>
								</Form.Item>
								<Form.Item label="联系人:" name="contact" rules={[{ required: true, message: '联系人姓名不能为空' }]}>
									<Input type="text" placeholder="请填写联系人姓名" />
								</Form.Item>
								<Form.Item
									validateTrigger="onBlur"
									label="联系电话:"
									name="tel"
									// rules={[
									// 	{
									// 		required: false,
									// 		pattern: new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/, 'g'),
									// 		message: '请输入正确的手机号码',
									// 	},
									// ]}
								>
									<Input placeholder="请填写联系电话" />
								</Form.Item>
								<Form.Item label="单位地址:" name="address">
									<Input.TextArea showCount maxLength={150} rows={4} placeholder="请填写单位地址" />
								</Form.Item>
								<Form.Item label="备注:" name="remark">
									<Input.TextArea showCount maxLength={500} rows={4} placeholder="请填写备注" />
								</Form.Item>
								<Space>
									<Button type="primary" htmlType="submit" style={{ marginLeft: 80 }}>
										保存
									</Button>
									<Button onClick={handleCancel} style={{ marginLeft: 40 }}>
										返回
									</Button>
								</Space>
							</Form>
						</Modal>
					</div>
				</Space>
			</Form>
			<Spin spinning={loading} tip="加载中...">
				<Table
					size="small"
					bordered
					columns={columns}
					scroll={{ y: 'calc(100vh - 290px)' }}
					rowKey="email"
					dataSource={data}
				/>
			</Spin>
		</>
	);
};
